package malus.shaofeng.com.beiwomusic.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.callback.BitmapLoadCallBack;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;


import malus.shaofeng.com.beiwomusic.R;
import malus.shaofeng.com.beiwomusic.adapter.NewStoryContentAdapter;
import malus.shaofeng.com.beiwomusic.model.Album;
import malus.shaofeng.com.beiwomusic.model.Artist;
import malus.shaofeng.com.beiwomusic.model.Comment;
import malus.shaofeng.com.beiwomusic.model.Content;
import malus.shaofeng.com.beiwomusic.model.ImageContent;
import malus.shaofeng.com.beiwomusic.model.NewStory;
import malus.shaofeng.com.beiwomusic.model.NewStoryMusic;
import malus.shaofeng.com.beiwomusic.model.NewStoryMusicLyric;
import malus.shaofeng.com.beiwomusic.model.TextContent;
import malus.shaofeng.com.beiwomusic.model.User;
import malus.shaofeng.com.beiwomusic.utils.BitmapHelper;
import malus.shaofeng.com.beiwomusic.utils.Constants;
import malus.shaofeng.com.beiwomusic.utils.SPHelper;
import malus.shaofeng.com.beiwomusic.view.ScrollChangeScrollView;
import malus.shaofeng.com.beiwomusic.view.SildingFinishLayout;

@ContentView(R.layout.new_story_details)
public class NewStoryDetailActivity extends Activity
        implements SildingFinishLayout.OnSildingFinishListener, View.OnClickListener {

    @ViewInject(R.id.newStory_detail_slidingFinish)
    private SildingFinishLayout sildingFinishLayout;
    @ViewInject(R.id.detail_loading)
    private LinearLayout loading;
    @ViewInject(R.id.loading_img)
    private ImageView loading_img;
    @ViewInject(R.id.detail_music_name)
    private TextView music_name;
    @ViewInject(R.id.detail_music_img)
    private ImageView music_img;
    @ViewInject(R.id.detail_view_title)
    private TextView view_title;
    @ViewInject(R.id.detail_face_uri)
    private ImageView face_uri;
    @ViewInject(R.id.detail_sex)
    private ImageView sex;
    @ViewInject(R.id.detail_nickname)
    private TextView nickname;
    @ViewInject(R.id.detail_content)
    private ListView content;
    @ViewInject(R.id.new_story_detail_scroll)
    private ScrollChangeScrollView scrollView;
    @ViewInject(R.id.new_story_detail_change_layout)
    private LinearLayout change_layout;
    @ViewInject(R.id.new_story_detail_bar)
    private ImageView bar;
    @ViewInject(R.id.new_story_detail_btn_group)
    private LinearLayout btn_group;
    private BitmapUtils bitmapUtils;
    private String path;
    private List<Content> contentList;
    private NewStoryContentAdapter adapter;

    @ViewInject(R.id.new_story_detail_btn_1)
    private ImageView btn_1;
    private NewStory storyExtra;
    private int position;
    private DbUtils dbUtils;

    @ViewInject(R.id.new_story_detail_album)
    private TextView detail_album;
    @ViewInject(R.id.story_detail_comment)
    ImageView storyDetailComment;
    @ViewInject(R.id.story_detail_like)
    ImageView storyDetailLike;
    //判断是否点赞
    boolean isLike;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);

        dbUtils = DbUtils.create(this, "storyFavourite.db");
        dbUtils.configAllowTransaction(true);
        dbUtils.configDebug(true);


        sildingFinishLayout.setOnSildingFinishListener(this);

        scrollView.registerTitle(music_name);
        scrollView.registerView(change_layout);
        scrollView.registerBar(bar);
        scrollView.registerBottom(btn_group);

        contentList = new LinkedList<>();
        Intent intent = getIntent();
        storyExtra = (NewStory)intent.getSerializableExtra("story");
        final NewStory story= storyExtra;
        position = intent.getIntExtra("position", 0);
        switch (position %4){
            case 0:
                loading_img.setImageResource(R.drawable.loading_1);
                break;
            case 1:
                loading_img.setImageResource(R.drawable.loading_2);
                break;
            case 2:
                loading_img.setImageResource(R.drawable.loading_3);
                break;
            case 3:
                loading_img.setImageResource(R.drawable.loading_4);
                break;
        }

        music_name.setText(story.getMusic().getArtists().get(0).getArtist_name()+" "+story.getMusic().getMusic_name());
        String image_uri = story.getImage_uri();
        if (image_uri!=null){
            bitmapUtils = BitmapHelper.getBitmapUtils();
            path = BitmapHelper.getImageUrl(image_uri);
            bitmapUtils.display(music_img, path);
        }
        String viewTitle = story.getView_title();
        String s = viewTitle.replaceAll("\\|", "\n");
        view_title.setText(s);
        String faceUri = story.getUser().getFace_uri();
        if (faceUri!=null){
            path=BitmapHelper.getImageUrl(faceUri);
            bitmapUtils.display(face_uri,path, new BitmapLoadCallBack<ImageView>() {
                @Override
                public void onLoadCompleted(ImageView imageView, String s, Bitmap bitmap, BitmapDisplayConfig bitmapDisplayConfig, BitmapLoadFrom bitmapLoadFrom) {
                    int width = bitmap.getWidth();
                    Bitmap dst = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888);
                    Paint paint = new Paint();
                    paint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
                    Canvas canvas = new Canvas(dst);
                    canvas.drawCircle(width / 2, width / 2, width / 2, paint);
                    imageView.setImageBitmap(dst);
                }

                @Override
                public void onLoadFailed(ImageView imageView, String s, Drawable drawable) {

                }
            });
        }

        int sex_id = story.getUser().getSex();
        switch (sex_id){
            case 1:
                sex.setImageResource(R.drawable.image_content_girl);
                break;
            case 2:
                sex.setImageResource(R.drawable.image_content_boy);
                break;
        }

        nickname.setText(story.getUser().getNickname());

        adapter = new NewStoryContentAdapter(this, contentList);
        content.setAdapter(adapter);

        String content_url = story.getContent_url();
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET,content_url,new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> objectResponseInfo) {

                Log.d("content_url",objectResponseInfo.result.toString());
                String result = objectResponseInfo.result.toString();

                try {
                    JSONArray jsonArray = new JSONArray(result);
                    contentList.clear();
                    for (int i=0;i<jsonArray.length();i++){
                        JSONObject object = jsonArray.getJSONObject(i);
                        String type = object.optString("type");
                        if (type.equals("text")){
                            TextContent textContent = new TextContent();
                            textContent.parseJSON(object);
                            contentList.add(textContent);
                        }else if (type.equals("image")){
                            ImageContent imageContent = new ImageContent();
                            imageContent.parseJSON(object);
                            contentList.add(imageContent);
                        }
                    }

                    Log.d("contentList",contentList.size()+"");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Log.d("content_url",s);
            }
        });



        Animation anim= AnimationUtils.loadAnimation(this, R.anim.popupwindow_fade_out);
        anim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                 loading.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        loading.startAnimation(anim);

        btn_1.setOnClickListener(this);

    }



    @Override
    public void onSildingFinish() {
        finish();
        overridePendingTransition(0,R.anim.trans_slider_out);
    }

    @Override
    public void onBackPressed() {
        finish();
        overridePendingTransition(0, R.anim.trans_slider_out);
    }

    private Handler handler=new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    Toast.makeText(NewStoryDetailActivity.this,"收藏成功",Toast.LENGTH_LONG).show();
                    break;
                case 1:
                    Toast.makeText(NewStoryDetailActivity.this,"收藏失败",Toast.LENGTH_LONG).show();
                    break;
                case 2:
                    Toast.makeText(NewStoryDetailActivity.this,"已经收藏",Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };

    @Override
    public void onClick(View v) {

        if(v.getId()==R.id.new_story_detail_btn_1){

            new Thread(new Runnable() {
            @Override
            public void run() {
                User user = storyExtra.getUser();
                NewStoryMusic newStoryMusic = storyExtra.getMusic();
                NewStoryMusicLyric music_lyric = newStoryMusic.getMusic_lyric();
                Album album = newStoryMusic.getAlbum();
                List<Artist> artists = newStoryMusic.getArtists();
                int size = artists.size();
                for (int i=0;i< size;i++){
                    artists.get(i).setNewStoryMusic(newStoryMusic);
                }

                NewStory dbStoryById = null;
                try {
                    dbStoryById = dbUtils.findById(NewStory.class, storyExtra.getStory_id());
                } catch (DbException e) {
                    e.printStackTrace();
                }
                if (dbStoryById == null) {
                    try {
                        dbUtils.saveOrUpdate(storyExtra);
                        dbUtils.saveOrUpdate(user);
                        dbUtils.saveOrUpdate(newStoryMusic);
                        dbUtils.saveOrUpdate(music_lyric);
                        dbUtils.saveOrUpdate(album);
                        dbUtils.saveOrUpdateAll(artists);
                        handler.obtainMessage(0, null).sendToTarget();
                    } catch (DbException e) {
                        e.printStackTrace();
                        handler.obtainMessage(1, null).sendToTarget();
                    }
                }else if (dbStoryById!=null){
                    handler.obtainMessage(2, null).sendToTarget();
                }
            }
        }).start();

        }
    }

    @OnClick(R.id.story_detail_comment)
    public void comment(View v){
        Intent intent = new Intent(this,StoryCommentActivity.class);
        intent.putExtra(Constants.BundleKey.KEY_STORY,storyExtra);
        startActivity(intent);
    }

    @OnClick(R.id.new_story_detail_album)
    public void click(View v){
          Intent intent=new Intent(this,MusicDetailActivity.class);
          intent.putExtra("storyExtra",storyExtra);
          startActivity(intent);
          overridePendingTransition(R.anim.trans_activity_in,0);
    }
    @OnClick(R.id.story_detail_like)
    public void like(View view){
        if(isLike){
            Toast.makeText(this,"您已经赞过这篇文章啦",Toast.LENGTH_SHORT).show();
        }
        final HttpUtils httpUtils=new HttpUtils();
        String url = "http://kxai.cn/qms/ws/comment/byStory.json";
        String token = SPHelper.getInstance().getToken();
        if(TextUtils.isEmpty(token)){
            Toast.makeText(this,"请先登录",Toast.LENGTH_SHORT).show();
            return;
        }
        RequestParams params = new RequestParams();
        params.addBodyParameter("token",token);
        params.addBodyParameter("storyId",storyExtra.getStory_id()+"");
        httpUtils.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                Toast.makeText(NewStoryDetailActivity.this,"赞成功",Toast.LENGTH_SHORT).show();
                storyDetailLike.setImageDrawable(getResources().getDrawable(R.drawable.article_bt_support_select));
                isLike=true;
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(NewStoryDetailActivity.this, "点赞失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
